from socket import MSG_DONTWAIT, socket
from threading import Thread
from time import sleep


class Pipe(Thread):
    __slots__ = ['x', 'y', 'callback']

    def __init__(self, x: socket, y: socket) -> None:
        super().__init__()
        self.x, self.y = x, y
        self.loop = True
        self.callback = lambda: None

    def run(self) -> None:
        while self.loop:
            try:
                data = self.x.recv(1024, MSG_DONTWAIT)
                if not data:
                    break
                self.y.send(data)
            except BlockingIOError:
                sleep(0.001)
        self.callback()


class bridger:
    def __init__(self, x: socket, y: socket) -> None:
        self.x, self.y = x, y
        self.pxy = Pipe(x, y)
        self.pyx = Pipe(y, x)

    def start(self):
        def callback():
            self.pxy.loop = False
            self.pyx.loop = False

        self.pxy.callback = callback
        self.pyx.callback = callback
        self.pxy.start()
        self.pyx.start()

    pass

